from exts import db
from models.borrow_record import BorrowRecord
from response import Response


class Person(db.Model):
    __tablename__ = 'person'
    personId = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    age = db.Column(db.Integer, nullable=False)
    email = db.Column(db.String(100), unique=True, nullable=False)
    # 假设一个人可以有多个借阅记录
    borrow_records = db.relationship('BorrowRecord', backref='person', lazy=True)

    def to_dict(self):
        return {
            'personId': self.personId,
            'name': self.name,
            'age': self.age,
            'email': self.email
        }

    def get_link(self):
        return {
            'self': 'http://localhost:5000/records/{}'.format(self.record_id),
            'person': 'http://localhost:5000/persons/{}'.format(self.person_id),
            'book': 'http://localhost:5000/books/{}'.format(self.book_id)
        }

    @staticmethod
    def get_persons():
        try:
            persons = Person.query.all()
            persons_list = [person.to_dict() for person in persons]
            data = {
                'persons': persons_list,
                '_links': {
                    'self': 'http://localhost:5000/persons'}
            }
            return Response.make_response(data=data, message='获取记录成功！')
        except Exception as e:
            db.session.rollback()
            return Response.make_response(status='500', message=str(e))

    # 添加新的人员
    @staticmethod
    def add_person( personId, name, age, email):
        person = Person(personId=personId, name=name, age=age, email=email)
        try:
            db.session.add(person)
            db.session.commit()
            data={
                '_links':{
                    'self':'http://localhost:5000/persons/{}'.format(person.personId)
                }
            }
            return Response.make_response(data=data,message='添加 新成员成功');
        except Exception as e:
            db.session.rollback()
            return Response.make_response(status='500',message=str(e))

    # 更新人员信息
    @staticmethod
    def update_person(personId, name, age, email):
        try:
            person = Person.query.filter_by(personId=personId).first()
            person.personId = personId
            person.name = name
            person.age = age
            person.email = email
            db.session.commit()
            data = {
                '_links':{
                    'self':'http://localhost:5000/persons/{}'.format(person.personId)
                }
            }
            return Response.make_response(data=data,message='更新用户信息成功')

        except Exception as e:
            db.session.rollback()
            return Response.make_response(status='500',message=str(e))

    # 删除人员信息
    @staticmethod
    def delete_person(personId):
        try:
            # 查询是否存在该人员记录
            person = Person.query.filter_by(personId=personId).first()

            if not person:
                return Response.make_response(status='404', message='未找到指定的人员')

            # 检查该人员是否有借阅记录
            if person.borrow_records:  # 如果存在借阅记录
                return Response.make_response(status='400', message='该用户正在借阅书籍，无法删除')

            # 删除该人员记录
            db.session.delete(person)
            db.session.commit()

            data = {
                '_links': {
                    'self': 'http://localhost:5000/persons/{}'.format(personId)
                }
            }
            return Response.make_response(data=data, message='删除用户信息成功')

        except Exception as e:
            db.session.rollback()
            return Response.make_response(status='500', message=str(e))
